package com.zcc.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class DruidConfig {
    //和yaml绑定
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DruidDataSource druidDataSource() {
        return new DruidDataSource();
    }

    //后台监控
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        //后台登录需要账号密码配置
        //Map存放登录配置
        HashMap<String, String> initParams = new HashMap<>();

        //增加配置
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "123456");
        //允许可以访问的用户
        initParams.put("allow", "");
        //禁止访问的用户，禁止IP
        //initParams.put("deny", "192.168.11.123");
        //设置参数
        bean.setInitParameters(initParams);
        return bean;
    }

    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>();
        //建立过滤器
        bean.setFilter(new WebStatFilter());
        //配置过滤规则存放对象
        HashMap<String, String> initParams = new HashMap<>();
        //例外对象
        initParams.put("exclusions", "*.js,*.css,*.ico,/druid/*");
        //给过滤器存放参数
        bean.setInitParameters(initParams);
        return bean;
    }
}
